#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* newTree(vector<int>& inorder, vector<int>& postorder, int& posI, int InLeft, int InRight)
    {
        if (InLeft > InRight)
            return nullptr;

        TreeNode* node = new TreeNode(postorder[posI]);
        int tmpLeft = InLeft;
        while (InLeft < InRight && inorder[InLeft] != postorder[posI])
        {
            ++InLeft;
        }
        --posI;

        node->right = newTree(inorder, postorder, posI, InLeft + 1, InRight);
        node->left = newTree(inorder, postorder, posI, tmpLeft, InLeft - 1);

        return node;
    }

    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int i = postorder.size() - 1;
        return newTree(inorder, postorder, i, 0, i);
    }
};